package com.sinothk.gpserver.config.annotation;

import com.sinothk.server.support.annotation.callback.BizException;
import com.sinothk.server.support.annotation.callback.ResponseResultAdvice;
import com.sinothk.server.support.entity.ResultCode;
import com.sinothk.server.support.entity.ResultData;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.text.MessageFormat;
import java.util.List;

/**
 * API统一返回引入：重写返回体 》 异常
 * 还需在 WebMvcConfigurer 中配置如下内容才有效：
 *     @Override
 *     public void addInterceptors(InterceptorRegistry registry) {
 *         // 可添加多个
 *         registry.addInterceptor(new ResponseResultInterceptor()).addPathPatterns("/**");
 *     }
 */

@Log4j2
@RestControllerAdvice
public class ResponseResultExceptionAdvice extends ResponseResultAdvice { // ResponseResultAdvice:自己定义

    //注册Logger，  推荐使用第一种不用每次更改类名
//    public final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 处理自定义的业务异常
     */
    @ExceptionHandler(value = BizException.class)
    public ResultData bizExceptionHandler(BizException bizException) {
        ResultData resultData;
        if (bizException.getResultCode() != null) {
            resultData = ResultData.failure(bizException.getResultCode());
        }else{
            resultData = ResultData.failure(bizException.getCode(), bizException.getMsg());
        }
        bizException.printStackTrace();
        return resultData;
    }

//    /**
//     * 处理shiro框架异常
//     *
//     * @param e
//     * @return
//     */
//    @ExceptionHandler(ShiroException.class)
//    public ResultData doHandleShiroException(ShiroException e) {
////        JsonResult r = new JsonResult();
////        r.setState(0);
////        if (e instanceof UnknownAccountException) {
////            r.setMessage("账户不存在");
////        } else if (e instanceof LockedAccountException) {
////            r.setMessage("账户已被禁用");
////        } else if (e instanceof IncorrectCredentialsException) {
////            r.setMessage("密码不正确");
////        } else if (e instanceof AuthorizationException) {
////            r.setMessage("没有此操作权限");
////        } else {
////            r.setMessage("系统维护中");
////        }
////        e.printStackTrace();
//        return ResultData.failure(600, e.getMessage());
//    }
//
//    @ExceptionHandler(value = RuntimeException.class)
//    public ResultData topException(RuntimeException e) {
//        e.printStackTrace();
//        return ResultData.failure(600, e.getMessage());
//    }

//    @ExceptionHandler(value = AuthenticationException.class)
//    public ResultData authenticationExceptionHandler(AuthenticationException e) {
////        ResultData resultData;
////        if (bizException.getResultCode() != null) {
////            resultData = ResultData.failure(bizException.getResultCode());
////        }else{
////            resultData = ResultData.failure(bizException.getCode(), bizException.getMsg());
////        }
////        log.error(JSON.toJSONString(resultData));
//        return ResultData.failure(600, e.getMessage());
//    }

    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public ResultData HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) {
        String errorMsg = MessageFormat.format(ResultCode.SYS_INVALID_REQUEST_ERROR.message(), exception.getMethod(), exception.getSupportedHttpMethods());
        exception.printStackTrace();
        return ResultData.failure(ResultCode.SYS_INVALID_REQUEST_ERROR.code(), errorMsg);
    }

    /**
     * HttpRequestMethodNotSupportedException
     * 处理系统异常
     */
    @ExceptionHandler(value = Exception.class)
    public ResultData exceptionHandler(Exception exception) {
        exception.printStackTrace();
        if (exception instanceof MethodArgumentNotValidException) {

            BindingResult bindingResult = ((MethodArgumentNotValidException) exception).getBindingResult();
            List<FieldError> fieldErrorsList = bindingResult.getFieldErrors();

            String msg = "";
            for (FieldError error : fieldErrorsList) {
                // 错误的属性
                String errorField = error.getField();
                //错误的提示
                String errorMsg = error.getDefaultMessage();
                msg = "[" + errorField + "]" + errorMsg;
            }
            log.error(msg);
            return ResultData.failure(ResultCode.SYS_ERROR.code(), msg);
        }
        return ResultData.failure(ResultCode.SYS_ERROR.code(), exception.getMessage());
    }

}
